<script setup lang="ts">
import { onBeforeMount, onMounted, ref, watch } from "vue";
import {
  Back,
  Right,
  Refresh,
  Search,
  Upload,
  Key,
} from "@element-plus/icons-vue";
import { ElLoading, ElMessage } from "element-plus";
import setTheme from "./libs/setTheme";
import { getCache, setCache } from "./libs/cache";
import axios from "axios";
// import path from "node:path";

import successVideo from "./assets/success2.wav";

const webViewPage = ref();
const serverUrl = ref("");

const memberUpdateTime = ref(""); //同步会员列表更新时间

const isOnTargetUrl = ref(true);

/**
 * 称是否需要去皮
 */
const isCroppingWeight = ref(
  localStorage.getItem("isCroppingWeight") == "true"
);
const croppingWeightValue = ref(localStorage.getItem("croppingWeightValue"));

watch(isCroppingWeight, (status) => {
  localStorage.setItem("isCroppingWeight", status ? "true" : "false");
});
watch(croppingWeightValue, (value) => {
  localStorage.setItem("croppingWeightValue", value ?? "");
});

/**
 * 是否全自动提交
 */
const isAutoSend = ref(localStorage.getItem("isAutoSend") == "true");

watch(isAutoSend, (value) => {
  localStorage.setItem("isAutoSend", value ? "true" : "false");
  refreshPage();
});

/**
 * 关联url的缓存
 */
let urlUserCodeCache: { [key: string]: boolean } = {};

/**
 * 向webview内发送快递单号
 */
function sendNumberToWebview(message: string) {
  console.log("serverGetUserCodeSuccess: message=" + message);
  if (urlUserCodeCache[message]) {
    return;
  }
  urlUserCodeCache[message] = true;

  console.log(
    "主进程写入用户标识: " +
      message +
      "    |    isOnTargetUrl:" +
      (isOnTargetUrl.value ? "true" : "false")
  );
  if (isOnTargetUrl.value) {
    // 注入js
    webViewPage.value.executeJavaScript(`
      window.$waitSetMessage = "${message}";
      if($("#weight").val() != ""){
        window.setNumber(window.$waitSetMessage)
        window.$waitSetMessage = ""
      }
    `);
    playSuccessMp3();
  }
}

onMounted(async () => {
  setTheme();

  /**
   * ! 开始监听内网IP
   */
  window.ipcRenderer.on("getListenIpSuccess", (event, message) => {
    serverUrl.value = message;
  });
  window.ipcRenderer.send("getListenIp");

  /**
   * ! 主进程注入js
   */
  window.ipcRenderer.on("serverGetUserCodeSuccess", (event, message) => {
    sendNumberToWebview(message);
  });

  // 文档载入完成事件
  webViewPage.value.addEventListener("dom-ready", (event: any) => {
    webViewPage.value.executeJavaScript(`
      window.__LYF__ = {
        // 是否重量去皮
        isCroppingWeight: "${
          isCroppingWeight.value ? "true" : "false"
        }" == "true",
        // 去皮重量 kg
        croppingWeightValue: Number("${croppingWeightValue.value}"),
        // 上一次更改后的重量
        lastWeightValue: "",
      }



      function setNumber(num) {

        let startValue = $("#user_code").val();

        var web = document.getElementById("web");
        web.value = num;
        web.focus();
        web.dispatchEvent(
          new KeyboardEvent('keypress', {
            key: 'Enter',
            keyCode: 13,
            code: 'Enter',
            which: 13,
            shiftKey: false,
            ctrlKey: false,
            metaKey: false
          })
        )

        if("${isAutoSend.value ? "true" : "false"}" == "true"){
          console.log("自动提交-监听开始: ");
          let now = function(){
            return new Date().getTime()
          };
          let timeout = now() + 10 * 1000;

          // 手动监听#user_code输入框改变事件
          let waitInputSet = (callback) => {
            if(timeout < now()){
              console.log("等待超时！");
              return;
            }
            setTimeout(() => {
              let val = String($("#user_code").val())
              if(
                val != startValue
                && val.length >= 3
              ){
                callback()
              }else{
                waitInputSet(callback)
              }
            }, 50);
          }
          
          waitInputSet(()=>{
            console.log("监听成功！开始点击确认=>");
            sub()
          })
        }else{
          console.log("无自动提交");
        }
      }
      window.setNumber = setNumber;



      var weight = document.getElementById("weight");
      if(weight){
        
        weight.addEventListener("keypress",(event)=>{
          if (event.key === 'Enter') {
            setTimeout(() => {
              
              let value = weight.value;
              if(
                window.__LYF__.lastWeightValue == value
                || !window.__LYF__.isCroppingWeight
                || !window.__LYF__.croppingWeightValue
                || (window.__LYF__.croppingWeightValue > 0.0000001 == false)
                || (value > 0.0000001 == false)
              ){
                return;
              }
              
              let bigNum = 1000000;
              let croValue = Math.floor(bigNum * value - bigNum * window.__LYF__.croppingWeightValue) / bigNum;
              if(croValue < 0)croValue = 0;
              weight.value = croValue;
              window.__LYF__.lastWeightValue = croValue;
              
            }, 30);

            setTimeout(() => {
              
              if(window.$waitSetMessage){

                setNumber(window.$waitSetMessage)
                window.$waitSetMessage = "";

              }
              
            }, 60);
          }
        })

      }
      
      
    `);
  });

  /**
   * ! 判断是否需要更新用户id库
   */
  let now = new Date().getTime();
  let lastUpdateUserCodeListTime = Number(
    await getCache("lastUpdateUserCodeListTime")
  );
  if (lastUpdateUserCodeListTime < now - 60 * 60 * 12 * 1000) {
    getUserCode();
  }

  // ! 监听webview中url改变事件
  webViewPage.value.addEventListener("did-start-navigation", (event: any) => {
    // url=> event.url
    isOnTargetUrl.value =
      event.url ==
      "https://www.leyifan.com/admin/ticketplus/package_receive_new_memari";

    urlUserCodeCache = {};
  });

  // ! 监听webview标题改变事件
  webViewPage.value.addEventListener("page-title-updated", (event: any) => {
    // title => event.title
    // ipcRenderer.send("wbTitleUpdate", event.title);
  });

  setTimeout(() => {
    // 打开调试工具页
    // webViewPage.value.openDevTools();
  }, 1000);
});

/**
 * 页面刷新事件
 */
function refreshPage() {
  console.log("刷新页面");
  webViewPage.value.reload();
}

/**
 * 页面回退事件
 */
const goBack = () => {
  console.log("回退页面");
  webViewPage.value.goBack();
};

/**
 * 页面前进事件
 */
const goForward = () => {
  console.log("回退页面");
  webViewPage.value.goForward();
};

function playSuccessMp3() {
  // const path = require("path");
  // 创建一个新的 audio 元素
  let audio = document.createElement("audio");
  // console.log("successVideo", successVideo);
  audio.src = successVideo; // 替换为你的音频文件路径
  audio.play();
  audio.onended = function () {
    console.log("音频播放完成");
  };
  audio.onerror = function (e) {
    console.error("音频加载失败", e);
  };
  setTimeout(() => {
    audio.remove();
  }, 2000);
}

setInterval(async () => {
  let lastUpdateUserCodeListTime = await getCache("lastUpdateUserCodeListTime");
  if (lastUpdateUserCodeListTime) {
    memberUpdateTime.value = getDay(Number(lastUpdateUserCodeListTime));
  } else {
    memberUpdateTime.value = "请更新";
  }
}, 1000);

function testTest() {
  sendNumberToWebview("m86453544108");
}

/**
 * 同步更新会员列表
 */
function getUserCode() {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  axios({
    method: "post",
    url: "https://api.mall.leyifan.cn/api/front/order/getShipedAndNotStockInProductIds",
    timeout: 30 * 1000,
  })
    .then(function (res) {
      loading.close();
      if (res?.data?.data && res?.data?.data.length > 0) {
        setCache("userCodeList", JSON.stringify(res.data.data));
        setCache("lastUpdateUserCodeListTime", new Date().getTime().toString());
        ElMessage({
          message: "更新完成",
          type: "success",
        });
      } else {
        ElMessage({
          message: "无数据",
          type: "error",
        });
      }
    })
    .catch(() => {
      loading.close();

      ElMessage({
        message: "更新出错",
        type: "error",
      });
    });
}

/**
 * 前往签收页面
 */
function goTargetPage() {
  webViewPage.value.loadURL(
    "https://www.leyifan.com/admin/ticketplus/package_receive_new_memari"
  );
}

/**
 * 处理时间
 */
function getDay(timestamp: any) {
  const now = Date.now();
  const diff = timestamp - now;
  const absoluteDiff = Math.abs(diff);

  const seconds = Math.floor(absoluteDiff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const years = Math.floor(days / 365);

  if (diff < 0) {
    if (seconds < 60) {
      return `${seconds}秒前`;
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 365) {
      return `${days}天前`;
    } else {
      return `${years}年前`;
    }
  } else {
    if (seconds < 60) {
      return `${seconds}秒后`;
    } else if (minutes < 60) {
      return `${minutes}分钟后`;
    } else if (hours < 24) {
      return `${hours}小时后`;
    } else if (days < 365) {
      return `${days}天后`;
    } else {
      return `${years}年后`;
    }
  }
}
</script>

<template>
  <div class="page">
    <div class="indexPage">
      <webview
        ref="webViewPage"
        src="https://www.leyifan.com/admin/ticketplus/package_receive_new_memari"
        :style="{
          width: '100vw',
          height: `calc( 100vh - 80px)`,
        }"
      ></webview>
    </div>

    <div class="servalPage">
      <div class="left">
        <el-input
          v-model="serverUrl"
          style="width: 360px; font-weight: bold; font-size: 18px"
          placeholder="当前服务器地址"
          size="large"
          input-style="color: #673ab7"
        >
          <template #prepend>服务器</template>
        </el-input>
        <el-checkbox
          v-model="isCroppingWeight"
          label="去皮"
          size="large"
          style="margin-left: 25px"
        />
        <el-input
          v-if="isCroppingWeight"
          v-model="croppingWeightValue"
          style="
            width: 170px;
            font-weight: bold;
            font-size: 18px;
            margin-left: 14px;
          "
          type="number"
          placeholder="重量"
          size="large"
        >
          <template #append>kg</template>
        </el-input>
      </div>
      <div>
        <!-- <el-button
          type="error"
          @click="testTest"
          class="btnSty"
        >
          测试
        </el-button> -->

        <el-checkbox
          v-model="isAutoSend"
          label="自动提交"
          size="large"
          style="margin-right: 20px"
        />

        <el-button
          type="success"
          @click="getUserCode"
          class="btnSty"
        >
          更新快递单号库
          <span style="font-size: 10px">({{ memberUpdateTime }})</span>
        </el-button>
        <el-button
          v-if="!isOnTargetUrl"
          type="success"
          @click="goTargetPage"
          class="btnSty"
        >
          开始签收
        </el-button>
        <el-button-group class="btnBox">
          <!-- <el-button
            type="primary"
            :icon="Search"
            @click="Searchkkkk"
            class="btnSty"
          /> -->
          <el-button
            type="primary"
            :icon="Back"
            @click="goBack"
            class="btnSty"
            title="网页回退"
          />
          <el-button
            type="primary"
            :icon="Refresh"
            @click="refreshPage"
            class="btnSty"
            title="刷新网页"
          />
          <el-button
            type="primary"
            :icon="Right"
            @click="goForward"
            class="btnSty"
            title="网页前进"
          />
        </el-button-group>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
}

.servalPage {
  width: calc(100vw - 20px);
  border-top: 1px dashed rgba(0, 0, 0, 0.2);
  height: 80px;
  padding: {
    left: 10px;
    right: 10px;
  }
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .left {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .btnBox {
    padding-left: 30px;
    .btnSty {
      height: 40px;
      margin: 0;
    }
  }
}
</style>
